import { defineStore } from 'pinia'
import { asyncRouterMap, constantRouterMap } from '@/router'
import {
  generateRoutesByFrontEnd,
  generateRoutesByServer,
  flatMultiLevelRoutes
} from '@/utils/routerHelper'
import { store } from '../index'
import { cloneDeep } from 'lodash-es'
import { Layout } from '@/utils/routerHelper'
import { useI18n } from '@/hooks/web/useI18n'

const { t } = useI18n()

const MyasyncRouterMap = [
  {
    path: '/user-manage',
    component: Layout,
    redirect: '/user-manage/all-users',
    name: 'UserManage',
    meta: {
      title: t('用户管理'),
      icon: 'ep:user-filled',
      alwaysShow: false
    },
    children: [
      {
        path: 'all-users',
        component: () => import('@/views/UsersManage/AllUsers/index.vue'),
        name: 'AllUsers',
        meta: {
          title: t('所有用户'),
          noCache: true,
          affix: false
        }
      },
      // {
      //   path: 'add-users',
      //   component: () => import('@/views/UserManage/AddUsers/index.vue'),
      //   name: 'AddUsers',
      //   meta: {
      //     title: t('新增用户'),
      //     noCache: true
      //   }
      // },
      {
        path: 'remain',
        component: () => import('@/views/UsersManage/Remain/index.vue'),
        name: 'Remain',
        meta: {
          title: t('留存情况'),
          noCache: true
        }
      },
      {
        path: 'advertising-total',
        component: () => import('@/views/UsersManage/AdvertisingTotal/index.vue'),
        name: 'AdvertisingTotal',
        meta: {
          title: t('广告条数筛选'),
          noCache: true
        }
      }
    ]
  },
  {
    path: '/earnings-manage',
    component: Layout,
    redirect: '/earnings-manage/real-earnings',
    name: 'EarningsManage',
    meta: {
      title: t('收益管理'),
      icon: 'ep:histogram',
      alwaysShow: true
    },
    children: [
      {
        path: 'real-earnings',
        component: () => import('@/views/EarningsManage/RealEarnings/index.vue'),
        name: 'RealEarnings',
        meta: {
          title: t('实际收益'),
          noCache: true
        }
      }
    ]
  }
]

export interface PermissionState {
  routers: AppRouteRecordRaw[]
  addRouters: AppRouteRecordRaw[]
  isAddRouters: boolean
  menuTabRouters: AppRouteRecordRaw[]
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routers: [],
    addRouters: [],
    isAddRouters: false,
    menuTabRouters: []
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers
    },
    getAddRouters(): AppRouteRecordRaw[] {
      return flatMultiLevelRoutes(cloneDeep(this.addRouters))
    },
    getIsAddRouters(): boolean {
      return this.isAddRouters
    },
    getMenuTabRouters(): AppRouteRecordRaw[] {
      return this.menuTabRouters
    }
  },
  actions: {
    generateRoutes(
      type: 'server' | 'frontEnd' | 'static' | 'isRole',
      routers?: AppCustomRouteRecordRaw[] | string[]
    ): Promise<unknown> {
      return new Promise<void>((resolve) => {
        let routerMap: AppRouteRecordRaw[] = []
        if (type === 'server') {
          // 模拟后端过滤菜单
          routerMap = generateRoutesByServer(routers as AppCustomRouteRecordRaw[])
        } else if (type === 'frontEnd') {
          // 模拟前端过滤菜单
          routerMap = generateRoutesByFrontEnd(cloneDeep(asyncRouterMap), routers as string[])
        } else if (type === 'static') {
          // 直接读取静态路由表
          routerMap = cloneDeep(asyncRouterMap)
        } else {
          //如果roleId不等于1用自己创建的路由
          routerMap = cloneDeep(MyasyncRouterMap)
        }
        // 动态路由，404一定要放到最后面
        this.addRouters = routerMap.concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: '404Page',
            meta: {
              hidden: true,
              breadcrumb: false
            }
          }
        ])
        // 渲染菜单的所有路由
        this.routers = cloneDeep(constantRouterMap).concat(routerMap)
        resolve()
      })
    },
    setIsAddRouters(state: boolean): void {
      this.isAddRouters = state
    },
    setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
      this.menuTabRouters = routers
    }
  },
  persist: {
    paths: ['addRouters', 'menuTabRouters', 'routers']
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}
